import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import { IpcKeys } from '../common/enums/ipc.enum'
import { terminalApi } from './terminal.api'
import { screenRecordingApi } from './screenRecording.api'
import { mockApi } from './mock.api'
const api = {
  // 调用保存对话框
  showSaveDialog: (options) => ipcRenderer.invoke(IpcKeys.SHOW_SAVE_DIALOG, options),
  // 调用文件写入
  writeFile: (filePath, content) => ipcRenderer.invoke(IpcKeys.WRITE_FILE, filePath, content),
  closeApp: () => ipcRenderer.invoke(IpcKeys.CLOSE_APP_EVENT),
  getAllFiles: (dir) => ipcRenderer.invoke(IpcKeys.GET_ALL_FILES, dir),
  getFileContent: (filePath) => ipcRenderer.invoke(IpcKeys.GET_FILE_CONTENT, filePath),
  // terminalApi
  ...terminalApi,
  ...screenRecordingApi,
  ...mockApi
}

// 暴露 API 到渲染进程的 window 对象
// 使用`contextBridge` API来向...暴露Electron API
// 仅当启用上下文隔离时才使用渲染器，否则
// 只需添加到DOM全局。
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('electronAPI', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.electronAPI = api
}
